package com.yby.es.confg;

import cn.hutool.core.util.StrUtil;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * @author lorabit
 * @since 2018/2/11
 */
@Configuration
@ConditionalOnClass(name = "org.elasticsearch.common.transport.InetSocketTransportAddress")
public class EsConfig {
    //@Value("${elastic.cluster.name}")
    //private String clusterName;
    @Value("${elastic.cluster.ip}")
    private String ip;
    @Value("${elastic.cluster.host}")
    private String host = "";
    @Value("${elastic.cluster.port}")
    private Integer port;
    @Value("${elastic.cluster.user}")
    private String user;

    @Bean(destroyMethod = "close")
    @ConditionalOnMissingClass(value = "org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate")
    public Client client() throws Exception {
        try {
            Settings.Builder builder = Settings.builder()
                    .put("client.transport.sniff", false);
            if (!StrUtil.isEmpty(user)) {
                builder.put("xpack.security.user", user);
            }
            Settings settings = builder.build();

            TransportClient client = new PreBuiltXPackTransportClient(settings);
            if (!StrUtil.isEmpty(host)) {
                client.addTransportAddress(new org.elasticsearch.common.transport.InetSocketTransportAddress(new InetSocketAddress(host, port)));
            } else {
                client.addTransportAddress(new org.elasticsearch.common.transport.InetSocketTransportAddress(InetAddress.getByName(ip), port));
            }
            return client;
        } catch (Exception e) {
            //log.error("ElasticSearchConfig init error");
            System.out.println("ElasticSearchConfig init error");
        }
        return null;
    }

//    @Override
//    public Class<?> getObjectType() {
//        return Client.class;
//    }
//
//    @Override
//    public boolean isSingleton() {
//        return true;
//    }


//    public void close() {
//        try {
//            Client client = SpringContextHelper.getBean(Client.class);
//            if (client != null) {
//                client.close();
//            }
//        } catch (Exception e) {
//            log.error("未知错误", e);
//        }
//    }


}
